package com.kstudio.videocapture.listfile;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.kstudio.videocapture.R;
import com.kstudio.videocapture.util.KLog;

public class KFileListDirectoryActivity extends Activity {
    private final KLog log = new KLog("KFileList");

    public static final String      PATH        = "DirectoryPath";
    public static final String      RESULTS     = "DirectoryResultPath";

    private Context mContext;
    private String  mPath;
    private String  mInputPath;

    private ListView                    mListView;
    private ArrayList<DirectoryItem>    mFileList;
    private DirectoryAdapter            mAdapter;

    private TextView                    mTextView;

    private String                      mSdCard;
    private String                      mExtsdCard;
    private String                      mRoot;

    private MenuItem                    mMenuDone;

    private Button                      mAddfolderDialogPositive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        log.i("***************** KFileListDirectoryActivity onCreate *****************");
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        if(intent != null) {
            mInputPath = mPath = intent.getStringExtra(PATH);
            log.i("Path = %s", mPath);
            if(mPath == null) {
                finishCancel();
                return;
            }
        } else {
            finishCancel();
            return;
        }

        setContentView(R.layout.file_action_activity);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

        mContext = this;

        init();
    }

    @Override
    protected void onResume() {
        log.i("***************** KFileListDirectoryActivity onResume *****************");

        super.onResume();
    }

    @Override
    protected void onPause() {
        log.i("***************** KFileListDirectoryActivity onPause *****************");

        super.onPause();
    }

    @Override
    protected void onStop() {
        log.i("***************** KFileListDirectoryActivity onStop *****************");

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        log.i("***************** KFileListDirectoryActivity onDestroy *****************");

        super.onDestroy();
    }

    /* Menu */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_fileaction, menu);
        mMenuDone = menu.findItem(R.id.menu_fileaction_done);
        if(mPath.equals(mInputPath)) {
            mMenuDone.setEnabled(false);
        } else {
            mMenuDone.setEnabled(true);
        }
        return true;
    }

    /* Event */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case android.R.id.home:
                finishCancel();
            return true;

            case R.id.menu_fileaction_addfolder:
                addfolderDialog(mContext);
            return true;

            case R.id.menu_fileaction_done:
                finishResult();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    private class OnListItemClickListenr implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int i, long l) {
            DirectoryItem fileData = (DirectoryItem) adapterview.getItemAtPosition(i);

            if(fileData.getFileType() == DirectoryItem.FOLDERUP) {
                if(mPath.equals(mSdCard) || mPath.equals(mExtsdCard)) {
                    mPath = makeFileList(mRoot);
                } else {
                    int separatorIndex = mPath.lastIndexOf(File.separator);

                    if(separatorIndex > 0)
                        mPath = makeFileList(mPath.substring(0, separatorIndex));
                }
            } else if(fileData.getFileType() == DirectoryItem.FOLDER) {
                mPath = makeFileList(fileData.getPath());
            }
        }
    }

    /* private */
    private void init() {
        mMenuDone = null;

        mFileList = new ArrayList<DirectoryItem>();
        mAdapter = new DirectoryAdapter(this, mFileList);

        mTextView = (TextView)findViewById(R.id.fileaction_path);

        mListView = (ListView)findViewById(R.id.fileaction_list);

        mPath = makeFileList(mPath);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new OnListItemClickListenr());
    }

    private String makeFileList(String path) {
        String result = updateFileList(path);
        if(mMenuDone != null) {
            if(result.equals(mInputPath)) {
                mMenuDone.setEnabled(false);
            } else {
                mMenuDone.setEnabled(true);
            }
        }
        mTextView.setText(result);
        mAdapter.notifyDataSetChanged();
        return result;
    }

    private String updateFileList(String path) {
        /* Storage directory */
        Map<String, File> externalLocations = KFileListExternalStorage.getAllStorageLocations();
        mSdCard = externalLocations.get(KFileListExternalStorage.SD_CARD).getPath();
        mExtsdCard = null;
        if(externalLocations.size() > 1) {
            mExtsdCard = externalLocations.get(KFileListExternalStorage.EXTERNAL_SD_CARD).getPath();
        }
        mRoot = mSdCard.substring(0, mSdCard.lastIndexOf(File.separator));

        String currentpath = path;
        File[] files = new File(currentpath).listFiles();

        mFileList.clear();
        if(files == null) {
            mFileList.add(new DirectoryItem("..", DirectoryItem.FOLDERUP));
            return currentpath;
        } else if(path.equals(mRoot)) {
            mFileList.add(new DirectoryItem("..", DirectoryItem.FOLDER));
            if(mExtsdCard != null) {
                mFileList.add(new DirectoryItem(mExtsdCard, DirectoryItem.FOLDER));
            }
            return mRoot;
        }

        mFileList.add(new DirectoryItem("..", DirectoryItem.FOLDERUP));

        for(File file: files) {
            if(file.isDirectory() && !file.getName().startsWith(".")) {
                mFileList.add(new DirectoryItem(file.getPath(), DirectoryItem.FOLDER));
            }
        }

        return currentpath;
    }

    protected InputFilter filterDuplicate = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            String expected = new String();
            expected += dest.subSequence(0, dstart);
            expected += source.subSequence(start, end);
            expected += dest.subSequence(dend, dest.length());

            if(expected.length() == 0 || expected.startsWith(".")) {
                mAddfolderDialogPositive.setEnabled(false);
                return null;
            }

            for(DirectoryItem item : mFileList) {
                if(item.getFileType() == DirectoryItem.FOLDER) {
                    if(expected.equals(item.getName())) {
                        mAddfolderDialogPositive.setEnabled(false);
                        return null;
                    }
                }
            }

            mAddfolderDialogPositive.setEnabled(true);
            return null;
        }
    };

    private void addfolderDialog(Context context) {
        AlertDialog.Builder addfolderDialogBuilder = new AlertDialog.Builder(context);

        final EditText newFolderName = new EditText(context);
        newFolderName.setFilters(new InputFilter[] {filterDuplicate});
        newFolderName.setHint(R.string.Add_folder_name);

        addfolderDialogBuilder.setTitle(R.string.Add_folder_name);
        addfolderDialogBuilder.setView(newFolderName);

        addfolderDialogBuilder.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                String newName = mPath + File.separator + newFolderName.getText().toString();
                File newFolder = new File(newName);
                newFolder.mkdirs();
            }
        });

        addfolderDialogBuilder.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {

            }
        });

        AlertDialog addfolderDialog = addfolderDialogBuilder.show();
        mAddfolderDialogPositive = ((AlertDialog) addfolderDialog).getButton(AlertDialog.BUTTON_POSITIVE);
        mAddfolderDialogPositive.setEnabled(false);

    }

    private void finishResult() {
        Bundle extra = new Bundle();
        Intent intent = new Intent();

        extra.putString(RESULTS, mPath);
        intent.putExtras(extra);
        this.setResult(RESULT_OK, intent);
        this.finish();
    }

    private void finishCancel() {
        this.finish();
    }

    private class DirectoryItem {
        public static final int FOLDERUP    = 0x0001;
        public static final int FOLDER      = 0x0002;

        private String path;
        private int filetype;

        public DirectoryItem(String path, int filetype) {
            this.path = path;
            this.filetype = filetype;
        }

        /* get function */
        public String getPath() {
            return path;
        }

        public String getName() {
            int separatorIndex = path.lastIndexOf(File.separator);
            return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
        }

        public int getFileType() {
            return filetype;
        }
    }

    private class DirectoryAdapterWrapper {
        private View                mBase;
        private ImageView            mIcon;
        private TextView             mName;

        public DirectoryAdapterWrapper(View base) {
            this.mBase = base;

            this.mIcon = null;
            this.mName = null;
        }

        public ImageView getIcon() {
            if(mIcon == null) {
                mIcon = (ImageView)mBase.findViewById(R.id.fileaction_row_icon);
            }
            return mIcon;
        }

        public TextView getName() {
            if(mName == null) {
                mName = (TextView)mBase.findViewById(R.id.fileaction_row_name);
            }
            return mName;
        }
    }

    private class DirectoryAdapter extends ArrayAdapter<DirectoryItem> {
        private static final int ICON_FOLDER        = R.drawable.klist_folder;

        private final LayoutInflater         mInflater;

        public DirectoryAdapter(Context context, ArrayList<DirectoryItem> objects) {
            super(context, 0, objects);

            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            DirectoryAdapterWrapper viewWrapper;

            if(view == null) {
                view = mInflater.inflate(R.layout.file_action_row, null);
                viewWrapper = new DirectoryAdapterWrapper(view);
                view.setTag(viewWrapper);
            } else {
                viewWrapper = (DirectoryAdapterWrapper)view.getTag();
            }

            final DirectoryItem data = this.getItem(position);

            if(data != null) {
                if(data.getFileType() == DirectoryItem.FOLDERUP) {
                    viewWrapper.getIcon().setImageResource(ICON_FOLDER);
                    viewWrapper.getName().setText(data.getName());
                } else if(data.getFileType() == DirectoryItem.FOLDER) {
                    viewWrapper.getIcon().setImageResource(ICON_FOLDER);
                    viewWrapper.getName().setText(data.getName());
                }
            }
            return view;
        }
    }
}
